package com.markyao.controller;

import com.markyao.dao.pojo.*;
import com.markyao.miaosha.Const;
import com.markyao.miaosha.GoodsKey;
import com.markyao.mq.MiaoshaMessage;
import com.markyao.mq.MqSender;
import com.markyao.service.*;
import com.markyao.service.impl.UserServiceImpl;
import com.markyao.vo.Result;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;

@RestController
@RequestMapping("miaosha")
public class MiaoshaController implements InitializingBean {

    private static HashMap<Integer,Boolean> isOverMap=new HashMap<>();
    @Autowired
    private MiaoshaGoodService miaoshaGoodService;
    @Autowired
    private RedisService redisService;
    @Autowired
    UserService userService;
    @Autowired
    MiaoshaService miaoshaService;
    @Autowired
    OrderService orderService;
    @Autowired
    MqSender mqSender;
    /*
     * 系统初始化 -->implements InitializingBean
     */
    public void afterPropertiesSet() throws Exception {
        List<Product> goodsList = miaoshaGoodService.getSeckillGoodsList();
        if (goodsList == null) {
            return;
        }
        for (Product goods : goodsList) {
            //对redis进行初始化
            redisService.set(GoodsKey.getSeckillGoodsStock,
                    "" + goods.getId(),
                    goods.getMiaoshaCount(),
                    Const.RedisCacheExtime.GOODS_LIST);
            //对是否结束进行初始化
            isOverMap.put(goods.getId(), false);
        }
    }

    /*
    NO.1,点击秒杀开始，获取秒杀路径path
    1.1检查是否登录
    1.1.1先获取登录token,再发送token通过redis获取到登录信息user
    1.2获取秒杀路径,创建秒杀路径
    1.2.1 通过md5创建秒杀路径,再将秒杀路径存入redis
     */
    @GetMapping("getpath/{id}")
    public Result getMiaoshaPath(@PathVariable long id,HttpServletRequest request
                                 ) {
        String token = request.getHeader("Authorization");
        User user = userService.checkT(token);
        if (user == null) {
            return Result.fail(-999,"未登录");
        }
        String path = miaoshaService.createMiaoshaPath(user, id);
        return Result.success(0,"获取秒杀资格成功",path);
    }

    /*
    N0.2 获取成功之后，将path作为请求路径进入到此,
    2.1判断是否登录,通过redis进行判断获取
    2.2验证path,通过第一步
    2.3map标记
    2.4预减库存(redis)
    2.5判断是否已经秒杀到了
    2.6进入消息队列排队
     */
    @PostMapping(value = "/{path}/seckill")
    public Result list(Model model,
                                @RequestParam("goodsId") Integer goodsId,
                                @PathVariable("path") String path,
                                HttpServletRequest request) {
        String loginToken = request.getHeader("Authorization");
        User user = userService.checkT(loginToken);
        if (user == null) {
            return Result.fail(-999,"未登录");
        }
        //验证path
        boolean check = miaoshaService.checkPath(user, goodsId, path);
        if (!check) {
            return Result.fail(-777,"path不正确!请检查你的账号是否登录正确");
        }
        //减少redis访问
        boolean over = isOverMap.get(goodsId);
        if (over) {
            return Result.fail(-555,"活动已经结束!");
        }/**/
        //预减库存
        long stock = redisService.decr(GoodsKey.getSeckillGoodsStock, "" + goodsId);//gs10000011
        if (stock < 0) {
            isOverMap.put( goodsId, true);
            return Result.fail(-555,"已经被抢光啦!活动已经结束!");
        }
        //判断是否已经秒杀到了 -->订单表,访问数据库
        MiaoshaOrder order = miaoshaService.findOrderByUidAndGoodId(user.getUid(),goodsId);
        if (order != null) {
            //重复抢单是否应该把前面预减的库存加回去
            return Result.fail(-666,"不要重复抢单哦!");
        }
        //加入消息队列
        MiaoshaMessage mm = new MiaoshaMessage();
        mm.setUser(user);
        mm.setGoodsId(goodsId);
        mqSender.sendSeckillMessage(mm);
        return Result.success(123321,"排队中",null);//排队中
    }

    /*
    No.3 判断是否秒杀成功(客户端轮询)
    3.1判断是否登录
    3.2查询秒杀结果
     */
    @GetMapping(value = "/result/{gid}")
    public Result miaoshaResult(@PathVariable("gid") Integer gid, HttpServletRequest request) {
        String loginToken = request.getHeader("Authorization");
        User user = userService.checkT(loginToken);
        if (user == null) {
            return Result.fail(-999,"你还未登录!");
        }
        MiaoshaOrder order = miaoshaService.findOrderByUidAndGoodId(user.getUid(), gid);
        if (order!=null){
            return Result.success(111,"秒杀成功啦!",null);
        }
        if (isOverMap.get(gid)){
            return Result.fail(-555,"已经被抢光啦!活动已经结束!");
        }
        return Result.success(123321,"排队中",null);//排队中
    }

}
